package com.fs.mapper.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MybatisUtil {
    private static SqlSessionFactory sqlSessionFactory;
    private static ThreadLocal<SqlSession> tl = new ThreadLocal<>();

    static{
        InputStream in = null;
        try {
            in = Resources.getResourceAsStream("mybatis-config.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
    }
    public static SqlSession getSqlSession(){
        SqlSession sqlSession = tl.get();
        if(sqlSession == null){
            tl.set(sqlSessionFactory.openSession());
        }
        return tl.get();
    }
     public static <T> T getMapper(Class<T> clazz){
        return getSqlSession().getMapper(clazz);
     }

     public static void close(){
        SqlSession sqlSession = getSqlSession();
        if(sqlSession !=null){
            sqlSession.commit();
            sqlSession.close();
        }
        tl.remove();//删除线程中数据，
     }
}
